package com.yhsoft.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yhsoft.common.request.IDsInVo;
import com.yhsoft.common.response.PageResult;
import com.yhsoft.common.service.Po.TokenUser;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.common.utils.IDGenerator;
import com.yhsoft.common.vo.Result;
import com.yhsoft.sys.controller.Response.LoginOutVo;
import com.yhsoft.sys.controller.Response.UserByIdOutVo;
import com.yhsoft.sys.controller.Response.UserInfoListOutVo;
import com.yhsoft.sys.controller.Response.UserInfoOutVo;
import com.yhsoft.sys.controller.request.LoginInVo;
import com.yhsoft.sys.entity.CompanyInfo;
import com.yhsoft.sys.entity.User;
import com.yhsoft.sys.service.ICompanyInfoService;
import com.yhsoft.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-08-30
 */
@Api(tags = {"A-用户接口列表"})
@Slf4j
@RestController
@RequestMapping("/user")
// @CrossOrigin   跨域处理
public class UserController {
    @Resource
    private IUserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private ICompanyInfoService iCompanyInfoService;

//    @ApiOperation("查询所有用户")
//    @GetMapping("/getAllUser")
//    public Result<List<User>> getAllUser(){
//        List<User> list = userService.list();
//        return Result.success(list,"查询成功");
//    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<LoginOutVo> login(@RequestBody LoginInVo user){
        User loginUser = new User();
        loginUser.setUsername(user.getUsername());
        loginUser.setPassword(user.getPassword());
        log.info("登录ing........................用户输入密码为：{}",user.getPassword());
        LoginOutVo data = userService.login(loginUser);
        if(data != null){
            // 校验公司状态
            if(data.getCompanyId() != 0 && iCompanyInfoService.getById(data.getCompanyId()).getCompanyStatus().equals(0)){
                return Result.fail(20002,"该用户所属的公司已被禁用！");
            }
            return Result.success(data);
        }
        return Result.fail(20002,"用户名或密码错误");
    }

    @ApiOperation("登陆返回(废弃，暂时前端实现）")
    @GetMapping("/getUserInfoByToken")
    public Result<UserInfoOutVo> getUserInfo(){
        String token = TokenService.getAuthorizationToken();
        // 根据token获取用户信息
        UserInfoOutVo userInfoOutVo = userService.getUserInfo(token);
        if(userInfoOutVo != null){
            return Result.success(userInfoOutVo);
        }
        return Result.fail(20003,"登录信息无效，请重新登录");
    }

    @ApiOperation("退出登陆")
    @PostMapping("/logout")
    public Result<?> logout(){
        String token = TokenService.getAuthorizationToken();
        userService.logout(token);
        return Result.success();
    }

    @ApiOperation("分页查询用户列表")
    @GetMapping("/getUserList")
    public Result<PageResult<UserInfoListOutVo>> getUserList(@RequestParam(value = "username",required = false) String username,
                                                             @RequestParam(value = "phone",required = false) String phone,
                                                             @RequestParam(value = "pageNo") Long pageNo,
                                                             @RequestParam(value = "pageSize") Long pageSize){
        IPage<UserInfoListOutVo> user = userService.getUserList(username,phone,pageNo,pageSize);
        return Result.success(PageResult.valueOf(user));
    }

    @ApiOperation("新增/修改用户信息")
    @PostMapping("/addOrUpdateUser")
    public Result<?> addOrUpdateUser(@RequestBody UserByIdOutVo userInVo){
        if(!StringUtils.hasLength(userInVo.getUsername())){
            return Result.fail("请输入用户名称！");
        }else if(!StringUtils.hasLength(userInVo.getPassword())){
            return Result.fail("请输入用户密码！");
        }
        // 判断是新增还是修改
        TokenUser userinfo = TokenService.getUserBytoken();
        User user = new User();
        if(!StringUtils.hasLength(userInVo.getId())){
            //不能重复新增
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, userInVo.getUsername());
            List<User> users = userService.list(queryWrapper);
            if (users.size() > 0) {
                return Result.fail("电话号码已经存在，无法新增！");
            }
            user.setId(IDGenerator.generate16("WebUser"));
            user.setUsername(userInVo.getUsername());
            user.setPassword(passwordEncoder.encode(userInVo.getPassword()));
            user.setName(userInVo.getName());
            user.setAvatar(userInVo.getAvatar());
            // user.setRoleIdList(userInVo.getRoleIdList());
            user.setRole(userInVo.getRole());
            user.setCompanyId(userinfo.getCompanyId());
            user.setSysType(userinfo.getSysType());
            user.setDeleted(0);
            userService.addUser(user);
            return Result.success("新增用户成功！");
        }else{
            user = userService.getUserById(userInVo.getId());
            user.setUsername(userInVo.getUsername());
            // 判断密码是否修改
            if(!userInVo.getPassword().equals("********")){
                log.info("修改密码ing...............用户输入密码为：{}",userInVo.getPassword());
                user.setPassword(passwordEncoder.encode(userInVo.getPassword()));
            }
            user.setName(userInVo.getName());
            user.setAvatar(userInVo.getAvatar());
            //user.setRoleIdList(userInVo.getRoleIdList());
            user.setRole(userInVo.getRole());
            userService.updateUser(user);
            return Result.success("修改用户成功！");
        }
    }

    @ApiOperation("根据id获取用户信息")
    @GetMapping("/getUserById/{id}")
    public Result<UserByIdOutVo> getUserById(@PathVariable("id") String id){
        User user = userService.getUserById(id);
        if(user == null){
            return Result.fail("未查询到结果！");
        }
        UserByIdOutVo userByIdOutVo = new UserByIdOutVo();
        userByIdOutVo.setId(user.getId());
        userByIdOutVo.setUsername(user.getUsername());
        userByIdOutVo.setName(user.getName());
        userByIdOutVo.setPassword("********");
        userByIdOutVo.setAvatar(user.getAvatar());
        userByIdOutVo.setCreateTime(user.getCreateTime());
        userByIdOutVo.setRole(user.getRole());
        return Result.success(userByIdOutVo);
    }

    @ApiOperation("查看用户个人信息")
    @GetMapping("/getUserInfo")
    public Result<UserByIdOutVo> getUserInfo1(){
        User user = userService.getUserById(TokenService.getUserBytoken().getId());
        if(user == null){
            return Result.fail("未查询到结果！");
        }
        UserByIdOutVo userByIdOutVo = new UserByIdOutVo();
        userByIdOutVo.setId(user.getId());
        userByIdOutVo.setUsername(user.getUsername());
        userByIdOutVo.setName(user.getName());
        userByIdOutVo.setPassword("********");
        userByIdOutVo.setAvatar(user.getAvatar());
        userByIdOutVo.setCreateTime(user.getCreateTime());
        userByIdOutVo.setRole(user.getRole());
        return Result.success(userByIdOutVo);
    }

    @ApiOperation("删除用户")
    @PostMapping("/deleteUserById")
    public Result<?> deleteUserById(@RequestBody IDsInVo inVo){
        if(inVo.equals(null)){
            return Result.fail("请输入用户id");
        }
        userService.deleteUserById(inVo.getIds());
        return Result.success("删除用户成功");
    }

}
